package com.lzw.service.impl.superAdmin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lzw.mapper.superAdmin.SupplierManegeMapper;
import com.lzw.pojo.Admins;
import com.lzw.pojo.Suppliers;
import com.lzw.service.superAdmin.SupplierManegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SupplierManegeServiceImpl implements SupplierManegeService {

    @Autowired
    private SupplierManegeMapper supplierManegeMapper;

    @Override
    public List<Suppliers> list(Integer pageNum, Integer pageSize, String name, String phone, String companyName) {
        PageHelper.startPage(pageNum,pageSize);
        List<Suppliers> list = supplierManegeMapper.list(name,phone,companyName);
        Page<Suppliers> suppliers = (Page<Suppliers>) list;
        return suppliers;
    }

    @Override
    public void delete(List<Integer> ids) {
        supplierManegeMapper.delete(ids);
    }

    @Override
    public void add(Suppliers suppliers) {
        if (supplierManegeMapper.countByName(suppliers.getName()) > 0) {
            throw new IllegalArgumentException("管理员姓名已存在");
        }
        if (supplierManegeMapper.countByUsername(suppliers.getUsername()) > 0) {
            throw new IllegalArgumentException("用户名已存在");
        }
        if (supplierManegeMapper.countByPhone(suppliers.getPhone()) > 0) {
            throw new IllegalArgumentException("联系电话已存在");
        }
        supplierManegeMapper.add(suppliers);
    }

    @Override
    public void update(Suppliers suppliers) {
        Suppliers existing = supplierManegeMapper.getAdminById(suppliers.getSupplierId());

        //检查学生是否存在
        if (existing == null){
            throw new IllegalArgumentException("系统管理员不存在");
        }

        // 检查姓名是否修改
        if (!existing.getName().equals(suppliers.getName())
                && supplierManegeMapper.countByName(suppliers.getName()) > 0) {
            throw new IllegalArgumentException("管理员姓名已存在");
        }

        // 检查用户名是否修改
        if (!existing.getUsername().equals(suppliers.getUsername())
                && supplierManegeMapper.countByUsername(suppliers.getUsername()) > 0) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 检查电话是否修改
        if (!existing.getPhone().equals(suppliers.getPhone())
                && supplierManegeMapper.countByPhone(suppliers.getPhone()) > 0) {
            throw new IllegalArgumentException("联系电话已存在");
        }

        supplierManegeMapper.update(suppliers);
    }
}
